package ecmnext.client;

/***************************************************************/
/*                     SOFTWARE SECTION                        */
/***************************************************************/
/*
 * <p>Name: ECMNext</p>
 * <p>Description: Simulation of the platform of trading Software</p>
 * <p>Licence: General Public License</p>
 * <p>Organisation: EC Marseille</p>
 * <p>Persons involved in the project : groupe Plateforme de Trading</p>
 * <p>Current version: 1.0</p>
 */

/***************************************************************/
/*                       IMPORT SECTION                        */
/***************************************************************/

import java.net.*;
import java.io.*;
import ecmnext.utils.*;

/***************************************************************/
/*                   LogSender CLASS SECTION                   */
/***************************************************************/
/**
 * <p>Title : LogSender</p>
 * <p>Description : </p>
 * @author Xuewen YANG ET Antoine COUDERC
 * @version 1.0
 */

public class LogSender implements Runnable {

  private int port;

  /**
   * Lance automatiquement le logSender.
   * @param port int
   */
  public LogSender(int port) {
    this.port = port;
    (new Thread(this)).start();
  }

  /**
   * run
   */
  public void run() {

    File file = new File(Constants.CLIENT_LOG_FILE);
    if (!file.exists()) {
      Utils.logger.error("Logging file not found... (excepting "+ Constants.CLIENT_LOG_FILE + ")");
      return;
    }

    try {
      ServerSocket socketserver = new ServerSocket(port);
      while(true) {
        Socket socket = socketserver.accept();
        OutputStream out = new BufferedOutputStream(socket.getOutputStream());
        InputStream in = new BufferedInputStream(new FileInputStream(file));

        Utils.logger.debug("Reading " + in.available() + " bytes from the stream");
        byte[] buffer = new byte[in.available()];

          long s = in.read(buffer);
          Utils.logger.debug(s + " bytes read.");

          Utils.logger.debug("writing them on network...");
          out.write(buffer);
          out.flush();
          Utils.logger.debug("done.");

        Utils.logger.debug("Closing connection...");
        in.close();
        out.close();
        socket.close();
        Utils.logger.debug("done.");
      }
    }
    catch (IOException ex) {
      Utils.logger.debug(ex.getMessage());
    }

  }

}
